<!-- 搜索组件 -->
<template>
  <div class="search-main-box">
    <div class="logo-img" @click="goHome">
      <img src="../assets/img/logo/logo.jpeg" alt="网站Logo">
    </div>
    <div class="search-box">
      <div class="search-input">
        <el-input
          placeholder="请输入商品名称"
          v-model="keyword"
          clearable
          @keyup.enter.native="handleSearch">
        </el-input>
      </div>
      <div class="search-btn">
        <el-button 
          type="danger" 
          @click="handleSearch"
          icon="el-icon-search"
          :loading="loading">
          搜索
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request.js' // 导入封装好的request

export default {
  name: 'SearchBar',
  props: {
    isInSearchPage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keyword: '',
      loading: false
    }
  },
  methods: {
    goHome() {
      this.$router.push('/')
    },
    
    handleSearch() {
      if (!this.keyword.trim()) {
        this.$message.warning('请输入商品名称')
        return
      }
      
      this.loading = true
      
      if (this.isInSearchPage) {
        this.$emit('search', this.keyword.trim())
        this.loading = false
        return
      }
      
      // 使用封装好的request
      request.get(`/products/findgoods/${encodeURIComponent(this.keyword)}`)
        .then(res => {
          // 注意：由于拦截器已经返回response.data，这里直接使用res
          this.$router.push({
            name: 'SearchResults',
            query: { keyword: this.keyword },
            params: {
              results: res.data || [],
              fromSearch: true
            }
          })
        })
        .catch(error => {
          console.error('搜索请求失败:', error)
          this.$router.push({
            name: 'SearchResults',
            query: { keyword: this.keyword },
            params: {
              results: [],
              fromSearch: true
            }
          })
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped>
.search-main-box {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo-img {
  cursor: pointer;
  margin-right: 30px;
}

.logo-img img {
  height: 50px;
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 800px;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}
</style>